#--*--coding=utf-8--*--
#MaterialCodeGenerator7.py
#点击增加组，增加到3组后就不能再增加，后台报错line 73, in addDropdownGroup
#for option in self.rules['groups'][len(self.dropdownGroups)]['options']:
#IndexError: list index out of range



import chardet



import sqlite3

def init_db():
    conn = sqlite3.connect('material_codes.db')
    c = conn.cursor()
    c.execute('''CREATE TABLE IF NOT EXISTS material_codes (code TEXT PRIMARY KEY)''')
    conn.commit()
    conn.close()

init_db()


import sys
import json
import sqlite3
from PySide6.QtWidgets import (QApplication, QMainWindow, QVBoxLayout, QWidget, QComboBox, QLineEdit,
                                QPushButton, QLabel, QHBoxLayout, QMessageBox)
from PySide6.QtCore import Qt, QStringListModel

class MaterialCodeGenerator(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("物料编码生成器")
        self.setGeometry(100, 100, 800, 200)

        self.layout = QVBoxLayout()
        self.central_widget = QWidget()
        self.central_widget.setLayout(self.layout)
        self.setCentralWidget(self.central_widget)

        self.dropdownGroups = []
        self.resultLabel = QLabel("生成的编码: ")
        self.layout.addWidget(self.resultLabel)

        self.addGroupButton = QPushButton("增加组")
        self.addGroupButton.clicked.connect(self.addDropdownGroup)
        self.layout.addWidget(self.addGroupButton)

        self.removeGroupButton = QPushButton("删除组")
        self.removeGroupButton.clicked.connect(self.removeDropdownGroup)
        self.layout.addWidget(self.removeGroupButton)

        self.copyButton = QPushButton("复制编码")
        self.copyButton.clicked.connect(self.copyCode)
        self.layout.addWidget(self.copyButton)

        self.loadRules()
        self.addDropdownGroup()  # 初始添加一组

    def loadRules(self):
        with open('rules3.json', 'r') as file:
            self.rules = json.load(file)

    def addDropdownGroup(self):
        group_layout = QHBoxLayout()

        comboBox = QComboBox()
        model = QStringListModel()
        comboBox.setModel(model)
        for option in self.rules['groups'][len(self.dropdownGroups)]['options']:
            comboBox.addItem(option)
        comboBox.currentIndexChanged.connect(self.updateResult)

        searchBox = QLineEdit()
        searchBox.textChanged.connect(lambda text: self.filterComboBoxes(text, model))

        group_layout.addWidget(comboBox)
        group_layout.addWidget(searchBox)

        self.layout.insertLayout(len(self.dropdownGroups), group_layout)
        self.dropdownGroups.append((comboBox, searchBox, group_layout, model))

    def removeDropdownGroup(self):
        if len(self.dropdownGroups) > 1:
            lastGroup = self.dropdownGroups.pop()
            for widget in [lastGroup[0], lastGroup[1]]:
                widget.setParent(None)
            self.layout.removeItem(lastGroup[2])
        self.updateResult()

    def filterComboBoxes(self, text, model):
        model.setStringList([option for option in self.rules['groups'][len(self.dropdownGroups) - 1]['options'] if text.lower() in option.lower()])

    def updateResult(self):
        result = ""
        for comboBox, _, _, _ in self.dropdownGroups:
            selectedText = comboBox.currentText()
            if selectedText:
                result += selectedText + "."
        result = result.rstrip(".")
        if len(result) == 14:
            if not self.isUniqueCode(result):
                QMessageBox.warning(self, "警告", "该编码已存在！")
                return
            self.resultLabel.setText(f"生成的编码: {result}")
        else:
            self.resultLabel.setText("生成的编码: ")

    def isUniqueCode(self, code):
        conn = sqlite3.connect('material_codes.db')
        c = conn.cursor()
        c.execute("SELECT * FROM material_codes WHERE code=?", (code,))
        result = c.fetchone()
        conn.close()
        return result is None

    def copyCode(self):
        code = self.resultLabel.text().split(": ")[1]
        if code and len(code) == 14:
            clipboard = QApplication.clipboard()
            clipboard.setText(code)
            QMessageBox.information(self, "提示", "编码已复制到剪贴板！")
        else:
            QMessageBox.warning(self, "警告", "没有有效的编码可复制！")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MaterialCodeGenerator()
    ex.show()
    sys.exit(app.exec())
